package com.block.datapush.service.apipush;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.block.common.enums.ProfitSharingEnum;
import com.block.common.model.param.PushApiKeyParam;
import com.block.common.service.IMemberCommonService;
import com.block.common.service.LogFactory;
import com.block.common.service.impl.ApplicationInfoServiceImpl;
import com.block.datapush.enums.PushStatusEnum;
import com.block.datapush.model.PushQueryParam;
import com.block.datapush.model.dto.NoticeParamDTO;
import com.block.datapush.model.result.ProtocolParamResult;
import com.block.datapush.model.result.PushApiResult;
import com.block.datapush.service.IPushApiService;
import com.block.datapush.service.apipush.utils.YangXinHuaAESUtil;
import com.block.datapush.service.apipush.utils.YangXinHuaApibUtil;
import com.block.db.entity.*;
import com.block.db.mapper.DataMatchOrderInfoMapper;
import com.block.db.mapper.DataMatchOrderItemMapper;
import com.block.db.mapper.MerchantDataPushInfoMapper;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

/**
 * 汇信全国
 */
@Service
public class YangXinHuaApiBRatePushService implements IPushApiService {

    private static final Logger log = LogFactory.getPushLog();


    @Autowired
    MerchantDataPushInfoMapper merchantDataPushInfoMapper;
    @Autowired
    DataMatchOrderItemMapper dataMatchOrderItemMapper;
    @Autowired
    ApplicationInfoServiceImpl applicationInfoService;



    @Override
    public PushApiResult checkUser(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {

        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);


        String queryUrl = pushApiKeyParam.getCheckUrl();
        String mobileMd5 = memberSourceInfo.getMobileMd5().toLowerCase();
        String phoneHead = memberSourceInfo.getMobile();
        if(phoneHead.length() >= 9){
             phoneHead = phoneHead.substring(0, 9);
        }
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("phoneMd5", mobileMd5);
        paramMap.put("phoneHead",phoneHead);
        paramMap.put("name",memberSourceInfo.getRealname());
        paramMap.put("sex",memberSourceInfo.getSex()==1?"男":"女");
        paramMap.put("age",memberSourceInfo.getAge());
        paramMap.put("cityCode",memberSourceInfo.getCityCode());
        paramMap.put("loanAmt", YangXinHuaApibUtil.getLoanAmount(memberSourceInfo.getLoanAmount()));
        paramMap.put("loanTerm", YangXinHuaApibUtil.getLoanTerm(memberSourceInfo.getLoanTime()));
        paramMap.put("loanUse",YangXinHuaApibUtil.getYongTu(memberSourceInfo.getYongtu()));
        paramMap.put("education", YangXinHuaApibUtil.getXueli(memberSourceInfo.getXueli()));
        paramMap.put("car", YangXinHuaApibUtil.getCar(memberSourceInfo.getCar()));
        paramMap.put("house", YangXinHuaApibUtil.getHouse(memberSourceInfo.getHouse()));
        paramMap.put("social", YangXinHuaApibUtil.getShebao(memberSourceInfo.getShebao()));
        paramMap.put("fund", YangXinHuaApibUtil.getGjj(memberSourceInfo.getGjj()));
        paramMap.put("insurance", YangXinHuaApibUtil.getBaoxian(memberSourceInfo.getBaoxian()));
        paramMap.put("zhima", YangXinHuaApibUtil.getZhima(memberSourceInfo.getZhima()));
        paramMap.put("huabei", YangXinHuaApibUtil.getHuaBei(memberSourceInfo.getHuabei()));
        paramMap.put("baitiao", YangXinHuaApibUtil.getBaiTiao(memberSourceInfo.getBaitiao()));
        paramMap.put("creditStatus", YangXinHuaApibUtil.getYuqi(memberSourceInfo.getYuqi()));
        paramMap.put("profession", YangXinHuaApibUtil.getJob(memberSourceInfo.getGongzuo()));
        String job = YangXinHuaApibUtil.getJob(memberSourceInfo.getGongzuo());
        if(StrUtil.equals(job,"4")){
            paramMap.put("license", "1");
        }
        if(StrUtil.equals(job,"2")){
            paramMap.put("monthIncome", YangXinHuaApibUtil.getShouru(memberSourceInfo.getShouru()));
            paramMap.put("salaryType","2");
        }
        paramMap.put("ip", memberSourceInfo.getReqIp());
        String timeStamp = String.valueOf(System.currentTimeMillis());
        String requestId = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 32);
        paramMap.put("platform", "ANDROID");
        paramMap.put("timeStamp",timeStamp);
        Map<String, String> map = new HashMap<>();
        map.put("requestId", requestId);
        map.put("timeStamp", timeStamp);
        map.put("phoneMd5", mobileMd5);
        paramMap.put("sign", sign(convertMap2String(map), pushApiKeyParam.getApiSecret()));
        String encrypt = YangXinHuaAESUtil.encryptAESECB(JSON.toJSONString(paramMap), pushApiKeyParam.getApiKey());
        Map<String,Object> aceMap = new HashMap<>();
        aceMap.put("requestId",requestId);
        aceMap.put("channelCode",pushApiKeyParam.getApiCode());
        aceMap.put("data",encrypt);

        log.info("【阳薪花半流程分润】撞库开始【queryUrl】{}【paramMap】{} 【aceMap】{}", queryUrl, JSON.toJSONString(paramMap),JSON.toJSONString(aceMap));
        String result = HttpUtil.createPost(queryUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(aceMap))
                .execute().body();
        log.info("【阳薪花半流程分润】撞库结束【result】{}", result);


        JSONObject resultObject = JSON.parseObject(result);
        Integer code = resultObject.getInteger("code");
        String msg = resultObject.getString("message");


        pushApiResult.setCode(code + "");
        pushApiResult.setMessage(msg);
        pushApiResult.setParamInfo(JSON.toJSONString(paramMap));
        pushApiResult.setResultInfo(result);

        if (StrUtil.equals(String.valueOf(code), "1")) {
            JSONObject data = resultObject.getJSONObject("data");
            String status = data.getString("status");
            if (StrUtil.equals(String.valueOf(status), "1")){
                String url = data.getString("grantUrl");
                pushApiResult.setApproveUrl(url);
                pushApiResult.setOutOrderNo(requestId);
                pushApiResult.setStatus(PushStatusEnum.WAIT_APPROVE.getValue());
                pushApiResult.setSettleFlag(true);
                pushApiResult.setPushSuccess(true);
                extJson.put("outOrderNo",requestId);
                //进行分润操作
                String priceType = pushApiKeyParam.getPriceType();
                BigDecimal typeRate = pushApiKeyParam.getTypeRate();
                if(ProfitSharingEnum.PROFITPRICE.getValue().equals(priceType)){
                    BigDecimal price = data.getBigDecimal("price");
                    if(price == null || price.compareTo(new BigDecimal(0.00))== -1){
                        pushApiResult.setPushSuccess(false);
                        return pushApiResult;
                    }
                    BigDecimal priceRight = typeRate.multiply(price);
                    pushApiResult.setPrice(price);
                    pushApiResult.setPriceRight(priceRight);
                }
                return pushApiResult;
            }
        }
        return pushApiResult;
    }



    @Override
    public PushApiResult queryApprove(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        pushApiResult.setOrderNo(orderNo);
        return pushApiResult;
    }

    @Override
    public PushApiResult registerUser(String orderNo, String outOrderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        String requestUrl = pushApiKeyParam.getRegisterUrl();
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("phone", memberSourceInfo.getMobile());
        paramMap.put("name",memberSourceInfo.getRealname());
        paramMap.put("sex",memberSourceInfo.getSex()==1?"男":"女");
        paramMap.put("age",memberSourceInfo.getAge());
        paramMap.put("cityCode",memberSourceInfo.getCityCode());
        paramMap.put("loanAmt", YangXinHuaApibUtil.getLoanAmount(memberSourceInfo.getLoanAmount()));
        paramMap.put("loanTerm", YangXinHuaApibUtil.getLoanTerm(memberSourceInfo.getLoanTime()));
        paramMap.put("loanUse",YangXinHuaApibUtil.getYongTu(memberSourceInfo.getYongtu()));
        paramMap.put("education", YangXinHuaApibUtil.getXueli(memberSourceInfo.getXueli()));
        paramMap.put("car", YangXinHuaApibUtil.getCar(memberSourceInfo.getCar()));
        paramMap.put("house", YangXinHuaApibUtil.getHouse(memberSourceInfo.getHouse()));
        paramMap.put("social", YangXinHuaApibUtil.getShebao(memberSourceInfo.getShebao()));
        paramMap.put("fund", YangXinHuaApibUtil.getGjj(memberSourceInfo.getGjj()));
        paramMap.put("insurance", YangXinHuaApibUtil.getBaoxian(memberSourceInfo.getBaoxian()));
        paramMap.put("zhima", YangXinHuaApibUtil.getZhima(memberSourceInfo.getZhima()));
        paramMap.put("huabei", YangXinHuaApibUtil.getHuaBei(memberSourceInfo.getHuabei()));
        paramMap.put("baitiao", YangXinHuaApibUtil.getBaiTiao(memberSourceInfo.getBaitiao()));
        paramMap.put("creditStatus", YangXinHuaApibUtil.getYuqi(memberSourceInfo.getYuqi()));
        paramMap.put("profession", YangXinHuaApibUtil.getJob(memberSourceInfo.getGongzuo()));
        String job = YangXinHuaApibUtil.getJob(memberSourceInfo.getGongzuo());
        if(StrUtil.equals(job,"4")){
            paramMap.put("license", "1");
        }
        if(StrUtil.equals(job,"2")){
            paramMap.put("monthIncome", YangXinHuaApibUtil.getShouru(memberSourceInfo.getShouru()));
            paramMap.put("salaryType","1");
        }
        paramMap.put("ip", memberSourceInfo.getReqIp());
        paramMap.put("platform", "ANDROID");
        String timeStamp = String.valueOf(System.currentTimeMillis());
        paramMap.put("timeStamp",timeStamp);
        Map<String, String> map = new HashMap<>();
        map.put("requestId", outOrderNo);
        map.put("timeStamp", timeStamp);
        map.put("phone", memberSourceInfo.getMobile());
        paramMap.put("sign", sign(convertMap2String(map), pushApiKeyParam.getApiSecret()));
        MerchantDataPushInfo entityByOutOrderNoLock = merchantDataPushInfoMapper.getEntityByOutOrderNoLock(String.valueOf(pushApiKeyParam.getInfoId()), outOrderNo);
        DataMatchOrderItem dataMatchOrderItem = dataMatchOrderItemMapper.selectDataMatchOrderItemStatus(String.valueOf(entityByOutOrderNoLock.getId()), String.valueOf(pushApiKeyParam.getInfoId()));

        String orderId = String.valueOf(dataMatchOrderItem.getOrderId());
        String orderItemId = String.valueOf(dataMatchOrderItem.getId());
        ApplicationInfo appInfoByAppCode = applicationInfoService.getAppInfoByAppCode(memberSourceInfo.getAppCode());
        String protocolUrl = StrUtil.format("{}/page/newprotocol/{}/{}.html", appInfoByAppCode.getApiUrl(), orderId, orderItemId);
        paramMap.put("authUrl", protocolUrl);

        String encrypt = YangXinHuaAESUtil.encryptAESECB(JSON.toJSONString(paramMap), pushApiKeyParam.getApiKey());
        Map<String,Object> aceMap = new HashMap<>();
        aceMap.put("requestId",outOrderNo);
        aceMap.put("channelCode",pushApiKeyParam.getApiCode());
        aceMap.put("data",encrypt);

        log.info("【阳薪花半流程分润】导单开始【requestUrl】{}【paramMap】{}【aceMap】{}", requestUrl, JSON.toJSONString(paramMap),JSON.toJSONString(aceMap));
        String result = HttpUtil.createPost(requestUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(aceMap))
                .execute().body();
        log.info("【阳薪花半流程分润】导单结束【result】{}", result);

        JSONObject resultObject = JSON.parseObject(result);
        Integer code = resultObject.getInteger("code");
        String msg = resultObject.getString("message");
        JSONObject data = resultObject.getJSONObject("data");

        pushApiResult.setCode(code + "");
        pushApiResult.setMessage(msg);
        pushApiResult.setParamInfo(JSON.toJSONString(aceMap));
        pushApiResult.setResultInfo(result);

        if (StrUtil.equals(String.valueOf(code), "1")) {
            String status = data.getString("status");
            if (StrUtil.equals(String.valueOf(status), "1")){
                pushApiResult.setPushSuccess(true);
                pushApiResult.setSettleFlag(true);
                pushApiResult.setStatus(PushStatusEnum.SUCCESS.getValue());
                return pushApiResult;
            }
        }
        pushApiResult.setPushSuccess(false);
        pushApiResult.setSettleFlag(false);
        pushApiResult.setStatus(PushStatusEnum.FAILED.getValue());
        return pushApiResult;
    }

    @Override
    public PushApiResult queryResult(PushQueryParam pushQueryParam, PushApiKeyParam pushApiKeyParam, String extJson) throws Exception {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        return pushApiResult;
    }

    @Override
    public NoticeParamDTO getNoticeResultParam(String infoId, Map<String, String[]> parameterMap, String paramContent) {
        NoticeParamDTO noticeParamDTO = new NoticeParamDTO();

        noticeParamDTO.setOutFlag(true);
        noticeParamDTO.setSettleFlag(true);
        noticeParamDTO.setStatus(PushStatusEnum.SUCCESS.getValue());
        noticeParamDTO.setQueryResult(paramContent);
        JSONObject jsonObject = JSON.parseObject(paramContent);
        if (ObjectUtil.isEmpty(jsonObject)){
            noticeParamDTO.setStatus(PushStatusEnum.CALLBACK_FAILED.getValue());
            return noticeParamDTO;
        }
        String orderId = jsonObject.getString("orderId");

        MerchantDataPushInfo entityByOutOrderNoLock = merchantDataPushInfoMapper.getEntityByOutOrderNoLock(infoId, String.valueOf(orderId));
        if (ObjectUtil.isEmpty(entityByOutOrderNoLock) || PushStatusEnum.SUCCESS.getValue().equals(entityByOutOrderNoLock.getStatus())){
            noticeParamDTO.setStatus(PushStatusEnum.CALLBACK_FAILED.getValue());
        }
        noticeParamDTO.setOutOrderNo(orderId);
        noticeParamDTO.setMerchantDataPushInfo(entityByOutOrderNoLock);
        return noticeParamDTO;

    }

    @Override
    public JSONObject getNoticeResultReturn(Map<String, String[]> parameterMap, String paramContent, JSONObject extObject) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", 200);
        jsonObject.put("msg", "success");
        return jsonObject;
    }


    @Override
    public ProtocolParamResult getProtocolResult(MerchantBaseInfo merchantBaseInfo, MemberSourceInfo memberSourceInfo) {
        return null;
    }


    public static String sign(String contentString, String encryptKey) {
        contentString = contentString + encryptKey;
        String sign = DigestUtils.md5Hex(contentString);
        return sign;
    }

    public static String convertMap2String(Map<String, String> paramsMap) {
        StringBuffer content = new StringBuffer();
        List<String> keys = new ArrayList<>(paramsMap.keySet());
        Collections.sort(keys);
        int index = 0;
        for (int i = 0; i < keys.size(); i++) {
            String key = keys.get(i);
            String value = paramsMap.get(key);
            if (!key.isEmpty() && !value.isEmpty()) {
                content.append((index == 0 ? "" : "&") + key + "=" + value);
                index++;
            }
        }
        return content.toString();
    }


}
